// stores/notificationStore.ts
import { defineStore } from 'pinia'
import axios from 'axios'
import { ref, computed } from 'vue'

export const useNotificationStore = defineStore('notification', () => {
    const notices = ref<Notice[]>([])

    // 添加一个标记，记录是否已经全部标记为已读
    const allMarkedAsRead = ref(false)

    // 各类通知的计数（只统计未读）
    const noticeCounts = computed(() => {
        const counts = {
            all: 0,
            like: 0,
            comment: 0,
            collection: 0,
            follow: 0,
            message: 0
        }

        notices.value.forEach(notice => {
            if (!notice.isRead) {
                counts.all++
                counts[notice.type] = (counts[notice.type] || 0) + 1
            }
        })

        return counts
    })

    // 获取未读通知数量
    const getUnreadCount = async (userId: string) => {
        try {
            const { data } = await axios.get('/api/notice/unread-count', { params: { userId } })
            return data.count || 0
        } catch (error) {
            console.error('获取未读数量失败:', error)
            throw error
        }
    }

    // 获取通知列表
    const fetchNotices = async (userId: string) => {
        try {
            const { data } = await axios.get('/api/notice', { params: { userId } })
            notices.value = data.sort((a: Notice, b: Notice) =>
                new Date(b.time).getTime() - new Date(a.time).getTime()
            )
            allMarkedAsRead.value = data.every((n: Notice) => n.isRead)
            return notices.value
        } catch (error) {
            console.error('获取通知失败:', error)
            throw error
        }
    }

    // 标记单个通知为已读
    const markNoticeAsRead = async (noticeId: string) => {
        try {
            await axios.put(`/api/notice/${noticeId}/read`)
            const index = notices.value.findIndex(n => n.id === noticeId)
            if (index !== -1) {
                notices.value[index].isRead = 1
                notices.value = [...notices.value] // 触发响应式更新
            }
        } catch (error) {
            console.error('标记通知为已读失败:', error)
            throw error
        }
    }

    // 新增：标记所有通知为已读
    const markAllNoticesAsRead = async (userId: string) => {
        try {
            if (!allMarkedAsRead.value) {
                await axios.put(`/api/notice/mark-all-read`, { userId })
                notices.value.forEach(notice => {
                    notice.isRead = 1
                })
                allMarkedAsRead.value = true
            }
        } catch (error) {
            console.error('标记所有通知为已读失败:', error)
            throw error
        }
    }

    // 根据类型过滤通知
    const getNoticesByType = (type: string) => {
        if (type === 'all') return notices.value
        return notices.value.filter(notice => notice.type === type)
    }

    // 删除通知
    const deleteNotice = async (noticeId: string) => {
        try {
            await axios.delete(`/api/notice/${noticeId}`)
            notices.value = notices.value.filter(n => n.id !== noticeId)
        } catch (error) {
            console.error('删除通知失败:', error)
            throw error
        }
    }

    return {
        notices,
        noticeCounts,
        allMarkedAsRead,
        getUnreadCount,
        fetchNotices,
        markNoticeAsRead,
        markAllNoticesAsRead,
        getNoticesByType,
        deleteNotice
    }
})

interface Notice {
    id: string
    userId: string
    type: 'like' | 'comment' | 'collection' | 'follow' | 'message'
    text: string
    time: string
    isRead: number // 0=未读，1=已读
    url?: string
    commentText?: string
}